<template>
    <view class="history-item" @click="onClick">
        <view class="history-item-header">
            <view class="left">
                <icon class="ic-shiyanshi iconfont bs-shiyanshi" type=""></icon>
                <text class="lab-name">{{ item.sysName }}</text>
            </view>
            <view :class="['status', isExpired ? 'completed' : isInUse ? 'in-use' : item.stauts]">
                <text>{{ isExpired ? '已结束' : isInUse ? '使用中' : getStatusText(item.stauts) }}</text>
                <icon class="ic-status iconfont"
                    :class="isExpired ? 'bs-dui' : isInUse ? 'bs-zhuangtai' : getStatusIcon(item.stauts)"></icon>
            </view>
        </view>
        <view class="history-item-body">
            <view class="info-row">
                <view class="label-container">
                    <icon class="ic-shebei iconfont bs-shebei"></icon>
                    <text class="label">预约设备：</text>
                </view>
                <text class="value">{{ item.sbName }}</text>
            </view>
            <view class="info-row">
                <view class="label-container">
                    <icon class="ic-date iconfont bs-rili"></icon>
                    <text class="label">预约日期：</text>
                </view>
                <text class="value">{{ item.date }}</text>
            </view>
            <view class="info-row">
                <view class="label-container">
                    <icon class="ic-time iconfont bs-shijian"></icon>
                    <text class="label">预约时间：</text>
                </view>
                <text class="value">{{ formatTime(item.time) }}</text>
            </view>
            <view class="info-row">
                <view class="label-container">
                    <icon class="ic-person iconfont bs-yonghu"></icon>
                    <text class="label">预约人：</text>
                </view>
                <text class="value">{{ item.personName }}</text>
            </view>
        </view>
        <view class="cancel-btn" v-if="!isExpired && !isInUse && item.stauts == '已预约'" @click.stop="showCancelConfirm">
            <text>取消预约</text>
        </view>
        <view class="book-again-btn" v-if="item.stauts == '已取消' && !isExpired" @click.stop="bookAgain">
            <text>再次预约</text>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, computed } from 'vue'
import db from '@/api/database'

const props = defineProps({
    item: {
        type: Object,
        default: () => ({}),
    }
})

const emit = defineEmits(['click', 'refresh'])

// 判断是否在使用中
const isInUse = computed(() => {
    const now = new Date()
    const [year, month, day] = props.item.date.split('-').map(Number)
    const reservationDate = new Date(year, month - 1, day)

    // 如果不是当天，返回false
    if (reservationDate.getDate() !== now.getDate() ||
        reservationDate.getMonth() !== now.getMonth() ||
        reservationDate.getFullYear() !== now.getFullYear()) {
        return false
    }

    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()
    const currentTime = currentHour + currentMinute / 60

    // 时间段映射
    const timeSlotMap = {
        '1': { start: 8, end: 10 },  // 8:00-10:00
        '2': { start: 10, end: 12 }, // 10:00-12:00
        '3': { start: 14, end: 16 }, // 14:00-16:00
        '4': { start: 16, end: 18 }  // 16:00-18:00
    }

    // 检查当前时间是否在预约的时间段内
    return props.item.time.some(timeSlot => {
        const slot = timeSlotMap[timeSlot]
        if (!slot) return false
        return currentTime >= slot.start && currentTime < slot.end
    })
})

const isExpired = computed(() => {
    const now = new Date()
    const [year, month, day] = props.item.date.split('-').map(Number)
    const reservationDate = new Date(year, month - 1, day)

    // 如果日期已过，直接返回已结束
    if (reservationDate.getDate() < now.getDate() ||
        reservationDate.getMonth() < now.getMonth() ||
        reservationDate.getFullYear() < now.getFullYear()) {
        return true
    }

    // 如果是当天，检查时间
    if (reservationDate.getDate() === now.getDate() &&
        reservationDate.getMonth() === now.getMonth() &&
        reservationDate.getFullYear() === now.getFullYear()) {

        const currentHour = now.getHours()
        const currentMinute = now.getMinutes()
        const currentTime = currentHour + currentMinute / 60

        // 时间段映射
        const timeSlotMap = {
            '1': { start: 8, end: 10 },  // 8:00-10:00
            '2': { start: 10, end: 12 }, // 10:00-12:00
            '3': { start: 14, end: 16 }, // 14:00-16:00
            '4': { start: 16, end: 18 }  // 16:00-18:00
        }

        // 获取最后一个时间段的结束时间
        const lastTimeSlot = Math.max(...props.item.time)
        const lastSlot = timeSlotMap[lastTimeSlot]
        if (!lastSlot) return false

        // 如果当前时间超过最后一个时间段的结束时间，则显示已结束
        return currentTime >= lastSlot.end
    }

    return false
})

function onClick() {
    emit('click', props.item)
}

function formatTime(timeArray) {
    if (!Array.isArray(timeArray) || timeArray.length === 0) return '暂无'

    const timeMap = {
        '1': '8:00-10:00',
        '2': '10:00-12:00',
        '3': '14:00-16:00',
        '4': '16:00-18:00'
    }

    return timeArray.map(t => timeMap[t] || t).join(', ')
}

// 获取状态文本
function getStatusText(status) {
    if (isExpired.value) return '已结束'
    if (isInUse.value) return '使用中'

    const statusMap = {
        '已预约': '已预约',
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝',
        'cancelled': '已取消',
        'completed': '已完成',
        'in-use': '使用中'
    }
    return statusMap[status] || status
}

// 获取状态图标
function getStatusIcon(status) {
    if (isExpired.value) return 'bs-dui'
    if (isInUse.value) return 'bs-zhuangtai'
    if (status === '已取消') return 'bs-cuo'

    const iconMap = {
        '已预约': 'bs-dui',
        'pending': 'bs-dengdai',
        'approved': 'bs-dui',
        'rejected': 'bs-cuo',
        'cancelled': 'bs-cuo',
        'completed': 'bs-dui',
        'in-use': 'bs-zhuangtai',
        '已取消': 'bs-cuo'
    }
    return iconMap[status] || 'bs-dengdai'
}

// 显示取消确认弹窗
function showCancelConfirm() {
    uni.showModal({
        title: '确认取消',
        content: '确定要取消该预约吗？',
        success: async (res) => {
            if (res.confirm) {
                await cancelReservation()
            }
        }
    })
}

// 取消预约
async function cancelReservation() {
    try {
        const res = await db.collection('yyjl').doc(props.item._id).update({
            stauts: '已取消'
        })

        if (res.updated === 1) {
            uni.showToast({
                title: '取消预约成功',
                icon: 'success'
            })
            // 触发父组件刷新列表
            emit('refresh')
        } else {
            uni.showToast({
                title: '取消预约失败',
                icon: 'error'
            })
        }
    } catch (err) {
        console.error('取消预约失败:', err)
        uni.showToast({
            title: '取消预约失败',
            icon: 'error'
        })
    }
}

// 再次预约
function bookAgain() {
    uni.navigateTo({
        url: `/pages/reservationDetail/reservationDetail?id=${props.item.sbID}`
    })
}
</script>

<style lang="scss" scoped>
@import "/static/css/iconfont.css";

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.history-item {
    margin-bottom: 10px;
    border-radius: 12px;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.95);
    padding: 15px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    animation: fadeIn 0.5s ease-out;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    position: relative;

    &:active {
        transform: translateY(2px);
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
    }

    .history-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .left {
            display: flex;
            align-items: center;

            .ic-shiyanshi {
                color: #2196f3;
                font-size: 22px;
            }

            .lab-name {
                font-size: 16px;
                font-weight: bold;
                color: #333;
                margin-left: 8px;
            }
        }

        .status {
            display: flex;
            align-items: center;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;

            .ic-status {
                font-size: 14px;
                margin-left: 4px;
            }

            &.pending,
            &.已预约 {
                background-color: #e7f6ec;
                color: #52c41a;
            }

            &.approved {
                background-color: #f5f5f5;
                color: #f0ad4e;
            }

            &.rejected {
                background-color: #fef6e7;
                color: #f5222d;
            }

            &.cancelled,
            &.已取消 {
                background-color: #f5f5f5;
                color: #f0ad4e;
            }

            &.completed {
                background-color: #f5f5f5;
                color: #999;
            }

            &.in-use {
                background-color: #e6f7ff;
                color: #1890ff;
            }
        }
    }

    .history-item-body {
        .info-row {
            display: flex;
            margin-bottom: 10px;
            font-size: 14px;

            &:last-child {
                margin-bottom: 0;
            }

            .label-container {
                display: flex;
                align-items: center;
                min-width: 90px;

                .ic-shebei,
                .ic-date,
                .ic-time,
                .ic-person {
                    font-size: 16px;
                    color: #48d3cf;
                    margin-right: 5px;
                }

                .label {
                    color: #666;
                }
            }

            .value {
                color: #333;
                flex: 1;
            }
        }
    }
}

.cancel-btn {
    position: absolute;
    right: 15px;
    bottom: 15px;
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background-color: #fff5f5;
    border: 1px solid #ffa39e;
    border-radius: 4px;
    color: #f5222d;
    font-size: 12px;
    transition: all 0.3s ease;
    z-index: 2;

    &:active {
        transform: scale(0.95);
        background-color: #fff1f0;
    }

    .ic-cancel {
        font-size: 14px;
        margin-right: 4px;
    }
}

/* 再次预约按钮样式 */
.book-again-btn {
    position: absolute;
    right: 15px;
    bottom: 15px;
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 4px;
    color: #1890ff;
    font-size: 12px;
    transition: all 0.3s ease;
    z-index: 2;

    &:active {
        transform: scale(0.95);
        background-color: #d6f0ff;
    }
}
</style>